package com.ytkj.digitalConstruction.controller.weather;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.ytkj.digitalConstruction.HttpResult;

/**
 * 天气接口控制器
 *
 * @author liuht
 * @phone 13823600456
 * @email laupete@qq.com
 * @date 2018年2月24日
 */
@RestController
@RequestMapping("/weather")
public class WeatherController {

	@Autowired
	private RestTemplate restTemplate;

	private static String WEATHER_ALL = "http://tj.nineton.cn/Heart/index/all?city=%s";

	private static String WEATHER_HOUR = "http://tj.nineton.cn/Heart/index/future24h/?city=%s";

	/**
	 * 获取天气接口，包括全部天气和小时天气
	 * 
	 * @param cityCode
	 * @return
	 */
	@GetMapping("/gets/{cityCode}")
	public HttpResult get(@PathVariable("cityCode") String cityCode) {
		String all = restTemplate.getForObject(getUrl(cityCode, 0), String.class);
		String hour = restTemplate.getForObject(getUrl(cityCode, 1), String.class);
		JSONObject result = new JSONObject();
		result.put("weatherAll", JSONObject.parse(all));
		result.put("weatherHour", JSONObject.parse(hour));
		return new HttpResult().success().obj(result);
	}

	/**
	 * 获取天气接口地址
	 * 
	 * @param cityCode
	 * @param type，0-全部天气、1-小时天气
	 * @return
	 */
	private String getUrl(String cityCode, int type) {
		if (type == 0) {
			return String.format(WEATHER_ALL, cityCode);
		} else if (type == 1) {
			return String.format(WEATHER_HOUR, cityCode);
		}
		return "";
	}
}
